package com.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * 类似于Ajax
 * <p>
 * 1、异步执行
 * 2、完成回调 whenComplete
 * 3、失败回调 exceptionally
 *
 * @author xudong
 */
public class CompletableFutureDemo1 {
	public static void main(String[] args) {
		CompletableFuture<Integer> completableFuture = CompletableFuture
				.supplyAsync(() -> {
					System.out.println(Thread.currentThread() + " 异步任务");
					try {
						TimeUnit.SECONDS.sleep(3);
					} catch (InterruptedException e) {
						throw new RuntimeException(e);
					}
					int i = 10 / 0;

					return 1024;
				})
				// 完成时的回调， 是否异常都会执行
				.whenComplete((v, e) -> {
					System.out.println("执行 whenComplete");
					System.out.println(Thread.currentThread() + "  返回值 => " + v);
					System.out.println(Thread.currentThread() + "  异常 => " + e);
					throw new RuntimeException("----------");
				})
				// 异常时的回调 （未触发异常不会执行）
				.exceptionally((e) -> {
					System.out.println("执行 exceptionally");
					System.out.println(Thread.currentThread() + " 异常回调： " + e);
					return 2333;
				});


		System.out.println("回到主线程 ---");
		try {
			System.out.println("等到获取结果.....");
			System.out.println("最终结果： " + completableFuture.get());
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		} catch (ExecutionException e) {
			throw new RuntimeException(e);
		}

	}
}
